package cn.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/exportServlet")
public class ExportServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //读取储存的文件
        //判断本地有无保存对象的文件
        if(new File("D:/stu.txt").exists()){
            //告诉浏览器返回的数据类型,告诉浏览器数据的处理方式，作为附件下载
            response.setHeader("content-type",super.getServletContext().getMimeType(".txt"));
            response.setHeader("content-disposition","attachement;filename=stu.txt");
            //读取本地文件
            FileInputStream fis = new FileInputStream("D:/stu.txt");
            ServletOutputStream sos = response.getOutputStream();
            byte[] arr = new byte[1024];
            int len;
            //将本地文件读取到浏览器
            while ((len=fis.read(arr))!=-1){
                sos.write(arr,0,len);
            }
            fis.close();
        }else {
            //若无文件存在,提示信息后跳转
            response.setHeader("Refresh","2;" + super.getServletContext().getContextPath() + "/index.jsp");
            response.getWriter().print("暂无学生信息,请添加后重试,两秒钟后自动跳转");
        }

    }
}
